<template>
  <div>
    <el-card style="min-width: 1200px">
      <el-row>
        <div class="tableSelectWrap">
          <el-form ref="qiyeUserManForm" :model="commandForm" label-width="100px">
            <el-col :span="6">
              <el-form-item label="选择应用" prop="appId">
                <el-select
                  v-model="commandForm.appId"
                  style="width: 100%"
                  placeholder="请选择应用"
                >
                  <el-option
                    v-for="val of appList"
                    :key="val.id"
                    :label="val.appName"
                    :value="val.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="选择角色" prop="roleId">
                <el-select
                  v-model="commandForm.roleId"
                  style="width: 100%"
                  placeholder="请选择角色"
                >
                  <el-option
                    v-for="val of roleList"
                    :key="val.id"
                    :label="val.name"
                    :value="val.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-button class="width120" @click="resetForm('qiyeUserManForm')"
                >重置</el-button
              >
              <el-button type="primary" class="width120" @click="()=>{
               this.dataForm=JSON.parse(JSON.stringify(this.commandForm));
               this.getDataList()
              }"
                >查询</el-button
              >
            </el-col>
            <el-col :span="3" :offset="2">
              <el-button type="primary" class="width100" @click="goAdd()"
                >添加成员</el-button
              >
            </el-col>
          </el-form>
        </div>
      </el-row>
    </el-card>
    <el-card style="margin-top: 15px; min-width: 1200px">
      <el-table :data="dataList">
        <template slot="empty">
          <el-empty
            :image="require('@/assets/imgs/middleWork/k1.png')"
            :image-size="80"
            description="暂无相关数据"
          ></el-empty>
        </template>
        <el-table-column
          show-overflow-tooltip
          prop="headUrl"
          align="center"
          label="头像"
        >
          <template slot-scope="scope">
            <el-avatar
              v-if="scope.row.headUrl"
              :src="getImgUrl(scope.row.headUrl)"
            ></el-avatar>
            <el-avatar v-else :src="require('@/assets/imgs/geren/info3.png')"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="realName"
          align="center"
          label="姓名"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.realName ? scope.row.realName : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="username"
          align="center"
          label="邮箱"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.username ? scope.row.username : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="mobile"
          align="center"
          label="电话"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.mobile ? scope.row.mobile : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="appName"
          align="center"
          label="所属应用"
        >
          <template slot-scope="scope">
            <div
              v-if="scope.row.appNameList"
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              <span v-if="scope.row.appNameList.length > 2">
                <span>{{ scope.row.appNameList[0] }}、</span>
                <span>{{ scope.row.appNameList[1] }}</span>
                <span>{{
                  "等" + scope.row.appNameList.length + "个应用"
                }}</span>
              </span>
              <span v-else-if="scope.row.appNameList.length == 1">
                <span>{{ scope.row.appNameList[0] }}</span>
              </span>
              <span v-else-if="scope.row.appNameList.length == 2">
                <span>{{ scope.row.appNameList[0] }}、</span>
                <span>{{ scope.row.appNameList[1] }}</span>
              </span>
              <span v-else> </span>
            </div>
            <div v-if="!scope.row.appNameList">
              <div>-</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="roleName"
          align="center"
          label="角色"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.roleName ? scope.row.roleName : "-" }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column show-overflow-tooltip prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <div>{{scope.row.status === 1 ? '启用' : '停用'}}</div>
          </template>
        </el-table-column> -->
        <el-table-column
          show-overflow-tooltip
          prop="act"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text"
              >详情</el-button
            > -->
            <el-button
              v-if="!['sub_admin', 'main_admin'].includes(scope.row.userType)"
              @click="handleEdit(scope.row.id)"
              type="text"
              >编辑</el-button
            >
            <el-button
              v-if="!['sub_admin', 'main_admin'].includes(scope.row.userType)"
              @click="deleteUser(scope.row.id)"
              type="text"
              >删除</el-button
            >
            <el-button
              v-if="!['sub_admin', 'main_admin'].includes(scope.row.userType)"
              @click="handlePassword(scope.row.id)"
              type="text"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      layout="prev, pager, next, sizes, jumper"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :current-page="pageNum"
      :total="total"
      @current-change="pageCurrentChangeHandle"
      @size-change="pageSizeChangeHandle"
    >
    </el-pagination>
    <codeDialogVue
      codeId="3"
      :type="codeType"
      :codeDialog.sync="codeDialog"
      @codeState="codeStateFn"
    />
  </div>
</template>

<script>
import codeDialogVue from "@/components/codeDialog.vue";
import mixin from "@/mixins/mixin";
import crypto from "@/crypto";
export default {
  name: "userManagement",
  components: {
    codeDialogVue,
  },
  mixins: [mixin],
  data() {
    return {
      codeItem: "",
      codeType: "",
      codeDialog: false,
      commandForm: {
        roleId: "",
        appId: "",
      },
      mixinViewModuleOptions: {
        getDataListURL: "/sys/user/page",
        createdIsNeed:false,
      },
      dataList: [],
      appList: [],
      roleList: [],
    };
  },
  created() {
    this.dataForm=JSON.parse(JSON.stringify(this.commandForm))
    this.getDataList()
    this.$http.get("/api/app/get").then((res) => {
      if (res.code === "0000") {
        this.appList = res.data;
        this.appList.unshift({ id: "", appName: "所有" });
      }
    });
    this.$http.post("/role/all").then((res) => {
      if (res.code === "0000") {
        this.roleList = res.data;
        this.roleList.unshift({ id: "", name: "所有" });
      }
    });
  },
  methods: {
    codeStateFn(val) {
      if (val) {
        if (this.codeType == "SMS_BUSINESS_DELETE_USER") {
          this.deleteUser(this.codeItem);
        } else {
          this.goAdd();
        }
      }
    },
    goCode(val, item) {
      this.codeType = val;
      this.codeItem = item;
      this.codeDialog = true;
    },
    goAdd() {
      this.$router.push("/qiye/addUser");
    },
    getImgUrl(id) {
      return window.location.origin + `/merchantApi/oss/view?id=${id}`;
    },
    handleEdit(id) {
      this.$router.push({ name: "qiyeAddUser", query: { id } });
    },
    handlePassword(userId){
      this.$http.post('/sys/user/passwordReset', {userId}
      ).then(res => {
        if (res.code === '0000') {
          this.copyAppId(crypto.get(res.data))
          this.query()
        }
      })
    },
    copyAppId(value) {

    const input = document.createElement('input')
    document.body.appendChild(input)
    input.setAttribute('readonly', 'readonly')
    input.setAttribute('value', value)
    input.select()
    input.setSelectionRange(0, value.length)
    try {
      document.execCommand('copy')
    } catch (err) {//
    }
    document.body.removeChild(input);
      this.$message.success('密码重置成功,已复制密码！')


//       const input = document.createElement("input"); // 创建input对象
//       input.value = value; // 设置复制内容
//       document.body.appendChild(input); // 添加临时实例
//       let issafariBrowser =
// /Safari/.test(navigator.userAgent) &&
// !/Chrome/.test(navigator.userAgent);
// if (issafariBrowser) {
//   console.log(value.length);
// //safari浏览器单独处理
// input.setSelectionRange(0,value.length);
// } else {
// //其他浏览器
// input.select();
// }
//       document.execCommand("Copy"); // 执行复制
//       document.body.removeChild(input); // 删除临时实例
//       this.$message.success('密码重置成功,已复制密码！')


// const input = document.createElement("input"); // 创建input对象
//       input.value = value; // 设置复制内容
//       document.body.appendChild(input); // 添加临时实例
//       input.select(); // 选择实例内容
//       document.execCommand("Copy"); // 执行复制
//       document.body.removeChild(input); // 删除临时实例
   //       this.$message.success('密码重置成功,已复制密码！')

    },
    deleteUser(id) {
      this
          .$confirm("确定删除该成员?", "提示", {
            customClass: "confirm",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            type: "warning",
            center: true,
          })
          .then(() => {
            this.$http
        .post(
          `/sys/user/delete`,
          {
            id,
          }
        )
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("删除成功！");
            if (Number.isInteger((this.total - 1) / this.pageSize)) {
              this.pageNum = (this.total - 1) / this.pageSize;
              if (this.pageNum == 0) {
                this.pageNum = 1;
              }
            }
            this.query();
          }
        });
          });
    },
  },
};
</script>

<style scoped lang="scss">
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
